package org.ko.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class KOQRCode {

	
	/**
	 * @param path---解读的二维码路径
	 * @throws Exception
	 */
	public static Result read (String path) throws Exception {
		MultiFormatReader multiFormatReader = new MultiFormatReader();
		File file = new File(path);
		BufferedImage image = ImageIO.read(file);
		BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
		Result result = multiFormatReader.decode(binaryBitmap);
		return result;
	}
	
	
	/**
	 * @param width 生成图片的宽度
	 * @param height 生成图片的高度
	 * @param format 生成图片的格式
	 * @param content 生成图片的内容
	 * @param path 生成图片的放置路径
	 * @throws Exception
	 */
	public static void write (Integer width, Integer height, String format, String content, String path) throws Exception {
    	//定义二维码参数
    	Map<EncodeHintType, Object> params = new HashMap<EncodeHintType, Object>();
    	params.put(EncodeHintType.CHARACTER_SET, "utf-8");
    	params.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
    	params.put(EncodeHintType.MARGIN, 2);
    	//生成二维码
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, params);
		Path file = new File(path).toPath();
		MatrixToImageWriter.writeToPath(bitMatrix, format, file);
	}
}
